package com.colabo.j2ee.web.core.exception;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.colabo.j2ee.web.core.context.ContextUtil;
import com.colabo.j2ee.web.core.context.CoreInitInfo;
import com.colabo.j2ee.web.core.vo.SessionUserHolder;

/**
 * 异常信息的工具类
 */
public class ExpMessageUtil {
	protected final static Log LOGGER = LogFactory.getLog(ExpMessageUtil.class);

	private static final Map BUNDLE_LOCALE_CACHE = new HashMap();
	
	private static Locale locale = Locale.getDefault();
	static {
		try{
			locale = ((SessionUserHolder)ContextUtil.getBean(SessionUserHolder.BEAN_ID)).getLocale();
		}catch(Exception ex){
			LOGGER.warn("Use deafult locale");
		}
	}

	public static String getMessage(String name) {
		return getMessage(name, null, locale);

	}

	public static String getMessage(String name, Object[] arguments) {
		return getMessage(name, arguments, locale);
	}

	public static String getMessage(String name, Object[] arguments, Locale locale) {
		return getMessageByResource(parserResource(name), name, arguments, locale != null ? locale : Locale
				.getDefault());

	}

	protected static String getMessageByResource(String resource, String name, Object[] arguments, Locale locale) {
		String value = getMessageByResource(resource, name, locale);
		if (value == null) {
			return "";
		}
		if (value.trim().length() == 0) {
			return value;
		}

		if (arguments != null && arguments.length > 0) {
			// 如果用1.5，则可应用自动填箱的特性进行格式化，而不需要把arguments显示的封状成一个参数数组
			value = MessageFormat.format(value, arguments);
		}
		return value;
	}

	protected static String getMessageByResource(String resource, String name, Locale locale) {
		if (resource == null || resource.trim().length() == 0) {
			return "";
		}
		if (name == null || name.trim().length() == 0) {
			return "";
		}

		ResourceBundle bundle = getResourceBundle(resource, locale);
		if (bundle == null) {
			return "";
		}

		String value = null;
		try {
			value = bundle.getString(name);
		} catch (Exception e) {
			LOGGER.warn("{}", e);
		}
		return value != null ? value.trim() : "";
	}

	protected static ResourceBundle getResourceBundle(String resource, Locale locale) {
		if (resource == null || resource.trim().length() == 0 || locale == null) {
			return null;
		}

		String resourceCacheKey = resource + "_" + locale.toString();
		ResourceBundle result = (ResourceBundle) BUNDLE_LOCALE_CACHE.get(resourceCacheKey);
		if (result == null) {
			result = getBaseResourceBundle(resource, locale);
			if (result != null) {
				BUNDLE_LOCALE_CACHE.put(resourceCacheKey, result);
			}
		}
		return result;
	}

	/**
	 * 负责解析ErrorCode中的文件名 如E_App_001，则返回App
	 * 
	 * @param name
	 * @return 符合规则或者约定的文件名
	 */
	protected static String parserFileName(String name) {
		if (name == null || name.trim().length() == 0){
			return null;
		}
		String[] splits = name.split("_");
		if (splits == null || splits.length < 3){
			return null;
		} else{
			return splits[1].toLowerCase();
		}
	}

	/**
	 * 根据sysmessage对象的构造参数中的key解析对应的异常信息描述文件名
	 * 如key为E_Framework_001,那么对应的异常属性文件为msg-framework.properties
	 */
	protected static String parserResource(String name) {
		String fileName = parserFileName(name);
		return CoreInitInfo.getInstance().getMsgFileDirectory() + ".msg" + "-" + fileName;
	}

	/**
	 * 取出属性文件
	 */
	protected static ResourceBundle getBaseResourceBundle(String resource, Locale locale) {
		if (resource == null || resource.length() <= 0) {
			return null;
		}
		if (locale == null) {
			locale = Locale.getDefault();
		}
		ClassLoader loader = Thread.currentThread().getContextClassLoader();
		ResourceBundle bundle = null;

		try {
			bundle = ResourceBundle.getBundle(resource, locale, loader);
		} catch (MissingResourceException e) {
//			ReadableMessage msg = new ReadableMessage(CommonConstants.MSG_ERR_BASE_0032, new Object[] {  resource, locale.toString(),e.toString() });
//			LOGGER.error(msg.getMsgInfo());
			e.printStackTrace();
			return null;
		}
		if (bundle == null) {
//			ReadableMessage msg = new ReadableMessage(CommonConstants.MSG_ERR_BASE_0033, new Object[] {  resource, locale.toString()});
//			LOGGER.error(msg.getMsgInfo());
			
			return null;
		} else {
			return bundle;
		}
	}
}
